#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2014-08-19 23:08:12
# @Author  : shitao.tommy (hero007asd@gmail.com)
# @Link    : http://example.org
# @Version : $Id$

import os
from tornado.web import RequestHandler
from tornado import web, template
from web.handler.api import BaseApiHandler
from lib import moduleinfo
import renderhtml
import re

class ApidocHandler(RequestHandler):
    def get(self, apiname):
        try:
            modules = moduleinfo.get_module('web.handler.api.'+apiname.replace('/', '.'))
        except Exception, e:
            raise Exception('module not found')
        url = self.request.uri[:self.request.uri.index(apiname)]

        api_path = ''.join([os.getcwd(),"/web/handler/api"])

        headlist = listdir(api_path,url)

        doclist = []

        infodicts = []

        for member in dir(modules):
            headdict = {}
            member = getattr(modules, member)
            uripath = ''
            if hasattr(member, 'route_path'):
                uripath = '/' +member.route_path
            if isinstance(member, type) and issubclass(member, BaseApiHandler) and member!=BaseApiHandler :
                doclist.append(member.__doc__)
                anchor = member.__name__

                infodict = {}
                infodict['field'] = []
                infodict['rtfield'] = []
                infolist = str(member.__doc__).strip().splitlines()
                for i in infolist:
                    if '@title' in i:
                        infodict['title'] = i.strip()[6:]
                    elif '@description' in i:
                        infodict['desc'] = i.strip()[12:]
                    elif '@method' in i:
                        infodict['method'] = i.strip()[7:]
                    elif '@param' in i:
                        fielddict = {}
                        for f in i.split():
                            if i.split().index(f) == 1:
                                fielddict['fname'] = f
                            elif i.split().index(f) == 2:
                                fielddict['fdesc'] = f
                            elif i.split().index(f) == 3:
                                fielddict['fremark'] = f
                        infodict['field'].append(fielddict)
                    elif '@return' in i:
                        infodict['return'] = i.strip()[7:]
                    elif '@retfield' in i:
                        rtdict = {}
                        for rtf in i.split():
                            if i.split().index(rtf) == 1:
                                rtdict['rtname'] = rtf
                            elif i.split().index(rtf) ==2:
                                rtdict['rtdesc'] = rtf
                            elif i.split().index(rtf) ==3:
                                rtdict['rtremark'] = rtf
                        infodict['rtfield'].append(rtdict)
                    infodict['anchor'] = anchor
                    infodict['url'] = self.request.host + uripath
                infodicts.append(infodict)
        self.write(renderhtml.html_string(headlist, 'api接口1.0', infodicts))


def listdir(path,url,level=0):
    file_arr = []

    for i in os.listdir(path):
        new_path = ''.join([path, '/', i])
        if os.path.isdir(new_path):
            module_name = re.split(os.getcwd()+"/",new_path)[1].replace('/', '.')
            moduletmp = moduleinfo.get_module(module_name)
            if hasattr(moduletmp, 'file_name'):
                new_file = []
                head_list = []
                for x in os.listdir(new_path):
                    if x.endswith('.py') and x !='__init__.py':
                        new_2_path = ''.join([new_path,'/', x])
                        head_dict = {}
                        m_name = ''.join([re.split(os.getcwd()+"/",new_path)[1].replace('/', '.'),'.',x[:-3]])

                        m_tmp = moduleinfo.get_module(m_name)
                        if hasattr(m_tmp, 'head_title'):
                            head_dict['title'] = m_tmp.head_title
                        else:
                            head_dict['title'] = x[:-3]
                        pre = re.split(path ,new_path)[1]

                        if len(pre) > 0:
                            head_dict['url'] = ''.join([url,pre[1:],'/',x[:-3]])
                        else:
                            head_dict['url'] = ''.join([url,x[:-3]])
                        head_list.append(head_dict)
                file_arr.append({'mname':moduletmp.file_name,'mlist':head_list})
    return file_arr

